package com.che.libcommon.api;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;

public abstract class ProgressDialogObserver<T> extends ApiOptionalResultObserver<T> implements
    OnCancelListener{

  private ProgressDialog progressDialog;

  public ProgressDialogObserver(ProgressDialog progressDialog) {
    this.progressDialog = progressDialog;
    progressDialog.setOnCancelListener(this);
  }

  public ProgressDialogObserver(Context context,String title,String message) {
    if(context!=null){
      ProgressDialog dialog = new ProgressDialog(context);
      dialog.setTitle(title);
      dialog.setMessage(message);
      dialog.setIndeterminate(true);
      dialog.setCancelable(true);
      dialog.setOnCancelListener(this);
      this.progressDialog = dialog;
    }

  }

  public ProgressDialogObserver(Context context){
    this(context,null,"处理中，请稍后...");
  }

  @Override
  protected void onStart() {
    super.onStart();
    if(progressDialog != null){
      progressDialog.show();
    }
  }

  @Override
  protected void onComplete() {
    super.onComplete();
    try {
      if(progressDialog != null){
        progressDialog.dismiss();
      }
    } catch (Throwable e) {
      e.printStackTrace();
    }
  }

  @Override
  public void onCancel(DialogInterface dialog) {
    dispose();
  }
}
